//
//  ViewController.swift
//  声音文本编辑器
//
//  Created by 左忠飞 on 2021/8/10.
//

import Cocoa

class ViewController: NSViewController{

    let speechSynthesizer = NSSpeechSynthesizer()
    
    @IBOutlet var speakBtn: NSButton!
    @IBOutlet var stopBtn: NSButton!
    @IBOutlet var textView: NSTextView!
    @IBOutlet var indicator: NSProgressIndicator!

    override func viewDidLoad() {
        super .viewDidLoad()
        speechSynthesizer.delegate = self
        stopBtn.isEnabled = false
        indicator.isHidden = true
    }
    
    @IBAction func speakButtonClicked(_ sender:NSButton) {
        if textView.string.count > 0 {
            speechSynthesizer.startSpeaking(textView.string)
        }else{
            speechSynthesizer.startSpeaking("The document is empty")
        }
    }
    
    @IBAction func stopButtonClicked(_ sender:NSButton) {
        speechSynthesizer.stopSpeaking()
    }

}

extension ViewController:NSSpeechSynthesizerDelegate{
    func speechSynthesizer(_ sender: NSSpeechSynthesizer, willSpeakWord characterRange: NSRange, of string: String) {
        print("即将开始阅读:\(string),\(characterRange)")
        speakBtn.isEnabled = false
        stopBtn.isEnabled = true
        indicator.isHidden = false
        indicator.minValue = 0
        indicator.maxValue = Double(string.count)
        indicator.doubleValue = Double(characterRange.location + characterRange.length)
    }
    
    func speechSynthesizer(_ sender: NSSpeechSynthesizer, didFinishSpeaking finishedSpeaking: Bool) {
        print("阅读完成")
        speakBtn.isEnabled = true
        stopBtn.isEnabled = false
        indicator.isHidden = true
    }
}
